package com.bxd.baodan.list;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.WebViewPager;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.base.BaseGirdFragment_Sticky;
import com.bxd.baodan.item.ProductItem;
import com.bxd.baodan.item.ProductSelectBean.SelectDataBean;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.widget.MyPopupWindow;
import com.umeng.analytics.MobclickAgent;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CheXianFragment extends BaseGirdFragment_Sticky<ProductItem> {
    private SelectDataBean data;


    //三级标签列表
    private TagFlowLayout tagFlowLayout;
    private List<SelectDataBean.Cat3> thirdTagList = new ArrayList<>();
    private TagAdapter<SelectDataBean.Cat3> tagAdapter;

    //记录二级分类数据
    private Map<Integer, List<SelectDataBean.ItemBean>> secondTypeMap = new HashMap<>();

    //一级分类表格
    private GridView firstTypeGv;
    private List<SelectDataBean.ItemBean> firstTypeList = new ArrayList<>();
    private CommonAdapter<SelectDataBean.ItemBean> firstTypeAdapter;

    //二级分类表格
    private GridView secondTypePopGv;
    private List<SelectDataBean.ItemBean> secondTypeList = new ArrayList<>();
    private CommonAdapter<SelectDataBean.ItemBean> secondTypeAdapter;
    //二级被选择的item
    private SelectDataBean.ItemBean selectChildBean;
    //标识弹窗显示位置
    private View line;
    //弹窗
    private MyPopupWindow popMenu;
    public int currentPosition ;
    private int curThirdTagPosition = -1;


    public static CheXianFragment getInstance(SelectDataBean bean) {
        CheXianFragment fragment = new CheXianFragment();
        fragment.data = bean;
        return fragment;
    }


    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_chexian;
    }

    @Override
    protected Type getTypeToken() {
        return new TypeToken<List<ProductItem>>() {
        }.getType();
    }

    @Override
    public void preDone(View view) {
        line = view.findViewById(R.id.line);
        firstTypeGv = view.findViewById(R.id.gv);
        tagFlowLayout = view.findViewById(R.id.id_flowlayout);
        initPopMenu();

        int size = data.select.size();
        // 添加一级分类数据
        firstTypeList.clear();
        for (int i = 0; i < size; i++) {
            if (data.select.get(i).selectArray != null && data.select.get(i).selectArray.size() > 0) {
                SelectDataBean.ItemBean itemBean = data.select.get(i).selectArray.get(0);
                itemBean.paramName = data.select.get(i).paramName;
                firstTypeList.add(itemBean);
            }

        }

        //添加二级数据,因为二级数据会显示到一级数据上,所以要添加上paramName
        for (int i = 0; i < data.select.size(); i++) {
            String paramName = data.select.get(i).paramName;
            List<SelectDataBean.ItemBean> selectArray = data.select.get(i).selectArray;
            for (int j = 0; j < selectArray.size(); j++) {
                selectArray.get(j).paramName = paramName;
            }
            secondTypeMap.put(i, selectArray);
        }
        //添加推荐三级标签
        thirdTagList.clear();
        thirdTagList.addAll(data.cat3);
        setAdapter();

        firstTypeGv.setNumColumns(size);
        firstTypeGv.setAdapter(firstTypeAdapter);

        secondTypePopGv.setAdapter(secondTypeAdapter);

        tagFlowLayout.setAdapter(tagAdapter);
        autoRefresh();

    }

    @Override
    protected void setUsualNetUtil() {
        netUtil = new NetUtil(getActivity(), JsonApi.PRODUCT_LISTS);
        netUtil.setParams("cat1", data.id);
    }

    @Override
    protected int getItemLayout() {

        return R.layout.chexian_item;
    }

    @Override
    protected void convert(ViewHolder holder, final ProductItem item) {
        holder.setText(R.id.p_name, item.p_name);




        Glide.with(getActivity()).load(item.p_img).
                error(R.drawable.img_error).
                into((ImageView) holder.getView(R.id.p_image));



        holder.getView(R.id.p_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //item.p_url= "https://ztg.zhongan.com/promote/entrance/promoteEntrance.do?redirectType=h5&promotionCode=INST171047535012&productCode=PRD160436305017&promoteCategory=single_product&token=";
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_CP_cpxq");

                openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{item.p_url});
            }
        });


    }

    @Override
    protected String getArrayStr(String json_data) {
        return "list";
    }



    private void setAdapter() {
        firstTypeAdapter = new CommonAdapter<SelectDataBean.ItemBean>(getActivity(), firstTypeList, R.layout.product_select_text) {

            @Override
            public void convert(final ViewHolder holder, final SelectDataBean.ItemBean item) {
                final TextView textView = holder.getView(R.id.text);
                textView.setText(item.name);
                textView.setTextColor(getResources().getColor(R.color.gray_666));
                textView.setBackground(null);
                Drawable drawable = getResources().getDrawable(R.drawable.p_arrow_down_gray);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                textView.setCompoundDrawables(null, null, drawable, null);
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!popMenu.isShowing()) {
                            currentPosition = holder.getPosition();
                            Drawable drawable = getResources().getDrawable(R.drawable.p_arrow_down_green);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            textView.setTextColor(Color.parseColor("#37b059"));
                            textView.setCompoundDrawables(null, null, drawable, null);
                            textView.setBackground(getResources().getDrawable(R.drawable.green_str_white_sol));


                            //通知二级标签数据更新
                            secondTypeList.clear();
                            secondTypeList.addAll(secondTypeMap.get(currentPosition));
                            secondTypeAdapter.notifyDataSetChanged();
                            popMenu.showAsDropDown(line);
                        } else {
                            popMenu.dismiss();
                        }
                    }
                });
            }
        };


        secondTypeAdapter = new CommonAdapter<SelectDataBean.ItemBean>(getActivity(), secondTypeList, R.layout.product_select_pop_text) {

            @SuppressLint("ResourceType")
            @Override
            public void convert(ViewHolder holder, final SelectDataBean.ItemBean item) {
                final TextView tv = holder.getView(R.id.tv);
                tv.setText(item.name);
                if (selectChildBean != null && item.name.equals(selectChildBean.name)) {
                    tv.setTextColor(getResources().getColor(R.color.white));
                    tv.setBackground(getResources().getDrawable(R.drawable.product_pop_press));
                } else {
                    tv.setTextColor(getResources().getColor(R.color.black));
                    tv.setBackground(getResources().getDrawable(R.drawable.product_pop_nomal));
                }

                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        tv.setBackground(getResources().getDrawable(R.drawable.product_pop_press));
                        tv.setTextColor(getResources().getColor(R.color.white));

                        selectChildBean = item;
                        if (item.array != null && item.array.size() > 0) {
                            //通知三级标签更新
                            thirdTagList.clear();
                            thirdTagList.addAll(item.array);
                            tagAdapter.notifyDataChanged();
                        }

                        firstTypeList.remove(currentPosition);
                        firstTypeList.add(currentPosition, selectChildBean);
                        popMenu.dismiss();

                        netUtil.setParams(item.paramName, item.id); //二级分类传参  company  cat2 ,online
                        autoRefresh();
                    }
                });

            }
        };


        tagAdapter = new TagAdapter<SelectDataBean.Cat3>(thirdTagList) {
            @Override
            public View getView(FlowLayout parent, int position, SelectDataBean.Cat3 cat3) {
                final TextView tv = (TextView) getActivity().getLayoutInflater().inflate(R.layout.tv_1, tagFlowLayout, false);
                if (netUtil != null) {
                    netUtil.clearParams("cat3");
                }
                tv.setText(cat3.name);
                return tv;
            }
        };
        tagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_CP_ejbq");

                if (curThirdTagPosition == position) {
                    netUtil.clearParams("cat3");
                    curThirdTagPosition = -1;
                    autoRefresh();
                } else {
                    netUtil.setParams("cat3", thirdTagList.get(position).id);
                    curThirdTagPosition = position;
                    autoRefresh();
                }

                return true;
            }
        });

        tagFlowLayout.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {

            }
        });


    }


    private void initPopMenu() {

        View contentView = View.inflate(getActivity(), R.layout.popwin_supplier_gridview,
                null);

        popMenu = new MyPopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        popMenu.setOutsideTouchable(true);
        popMenu.setBackgroundDrawable(new BitmapDrawable());
        popMenu.setFocusable(true);
        popMenu.setAnimationStyle(R.style.popwin_anim_style);
        popMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            public void onDismiss() {
                //字体变灰色
                firstTypeAdapter.notifyDataSetChanged();
            }
        });
        secondTypePopGv = (GridView) contentView
                .findViewById(R.id.popwin_supplier_list_gv);
        contentView.findViewById(R.id.popwin_supplier_list_bottom)
                .setOnClickListener(new View.OnClickListener() {
                    public void onClick(View arg0) {
                        popMenu.dismiss();
                    }
                });

    }


}
